﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Xmart.Common
{
    public class DataUtils
    {

        /// <summary>
        /// 类型转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T To<T>(object obj)
        {
            var type = typeof(T);

            if (obj == null && obj == DBNull.Value)
            {
                return default(T);
            }
            else if (type == typeof(string) && !string.IsNullOrEmpty(obj.ToString()))
            {
                var method = Spring.Util.ReflectionUtils.GetMethod(obj.GetType(), "ToString", Type.EmptyTypes);
                return (T)method.Invoke(obj, new object[0]);
            }
            else if (type.IsValueType)
            {
                var method = Spring.Util.ReflectionUtils.GetMethod(type, "Parse", new Type[] { typeof(string) });
                return (T)method.Invoke(obj, new object[] { obj.ToString() });
            }

            return (T)obj;
        }
    }
}
